#include "stdafx.h"
#include "SimpleCamera.h"
#include "Globals.h"


SimpleCamera::SimpleCamera()
{
	m_maView.SetIdentity();
	m_maWorld.SetIdentity();

	m_bIsChanged = false;

	m_vPosition = Vector3(0.0f, 0.0f, 15.0f);
	m_fRotX = 0.0f;
	m_fRotY = 0.0f;
	m_fRotZ = 0.0f;

	CalculateWVMatrix();
} 

void SimpleCamera::CalculateWVMatrix()
{
	Matrix maRotX, maRotY, maRotZ;
	Matrix maRot;
	Matrix maTran;

	//Calculate World
	maRotX.SetIdentity().SetRotationX(m_fRotX);
	maRotY.SetIdentity().SetRotationY(m_fRotY);
	maRotZ.SetIdentity().SetRotationZ(m_fRotZ);
	maRot = maRotZ * maRotX * maRotY;
	maTran.SetIdentity().SetTranslation(m_vPosition);

	//World matrix
	m_maWorld = maRot * maTran;

	//Calculate View
	maRot.Transpose();
	maTran.m[3][0] *= -1.0f;	maTran.m[3][1] *= -1.0f;	maTran.m[3][2] *= -1.0f;

	//View matrix
	m_maView = maTran * maRot.Transpose();
}

Matrix SimpleCamera::GetWorldMatrix()
{
	return m_maWorld;
}

Matrix SimpleCamera::GetViewMatrix()
{
	return m_maView;
}


GLfloat fOffsetX, fOffsetY, fOffsetZ;
void SimpleCamera::Update(ESContext *esContext, GLfloat deltaTime)
{
	if(m_bIsChanged)
	{
		CalculateWVMatrix();
		Vector4 moveL = Vector4(fOffsetX, fOffsetY, fOffsetZ, 1.0f);
		Vector4 moveW = moveL * m_maWorld;
		m_vPosition = Vector3(moveW.x, moveW.y, moveW.z);
		fOffsetX = 0.0f;
		fOffsetY = 0.0f;
		fOffsetZ = 0.0f;
		m_bIsChanged = false;
	}
}

void SimpleCamera::MoveLeft(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetX = -offset;
}

void SimpleCamera::MoveRight(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetX = offset;
}

void SimpleCamera::MoveDown(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetY = -offset;
}

void SimpleCamera::MoveUp(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetY = offset;
}

void SimpleCamera::MoveBackward(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetZ = offset;
}

void SimpleCamera::MoveForward(GLfloat offset)
{
	m_bIsChanged = true;
	fOffsetZ = -offset;
}

void SimpleCamera::RotateLeft(GLfloat offset)
{
	m_bIsChanged = true;
	m_fRotY -= offset;
}

void SimpleCamera::RotateRight(GLfloat offset)
{
	m_bIsChanged = true;
	m_fRotY += offset;
}

void SimpleCamera::RotateDown(GLfloat offset)
{
	m_bIsChanged = true;
	m_fRotX -= offset;
}

void SimpleCamera::RotateUp(GLfloat offset)
{
	m_bIsChanged = true;
	m_fRotX += offset;
}